
/////////////////////////////////////////////////////////////////////////////////
//
//  泛型编码，模板编程。  ： 缘起
//
/////////////////////////////////////////////////////////////////////////////////

#include<iostream>

void swapInt(int &a, int &b)
{
    int tmp = a;
    a = b;
    b = tmp;
}

void swapDouble(double &a, double &b)
{
    double tmp = a;
    a = b;
    b = tmp;
}

// 利用模板实现通用交换函数。
template<typename T>
void swap(T &a, T &b)
{
    T tmp = a;
    a = b;
    b = tmp;
}

int main()
{
    int a1 = 9;
    int b1 = 8;
    std::cout << "a1 = " << a1 << ", b1 = " << b1<< std::endl;
    swapInt(a1, b1);
    std::cout << "a1 = " << a1 << ", b1 = " << b1<< std::endl;
    // 自动类型推导
    swap(a1, b1);
    std::cout << "a1 = " << a1 << ", b1 = " << b1<< std::endl;
    // 指定类型
    swap<int>(a1, b1);
    std::cout << "a1 = " << a1 << ", b1 = " << b1<< std::endl;

    std::cout << std::endl;

    double a2 = 9;
    double b2 = 8;
    std::cout << "a2 = " << a2 << ", b2 = " << b2<< std::endl;
    swapDouble(a2, b2);
    std::cout << "a2 = " << a2 << ", b2 = " << b2<< std::endl;
    swap(a2, b2);
    std::cout << "a2 = " << a2 << ", b2 = " << b2<< std::endl;
    swap<double>(a2, b2);
    std::cout << "a2 = " << a2 << ", b2 = " << b2<< std::endl;

    system("pause");
    return EXIT_SUCCESS;
}
